package com.alibaba.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.yygh.common.exception.YyghException;
import com.alibaba.yygh.hosp.repository.DepartmentRepository;
import com.alibaba.yygh.hosp.service.DepartmentService;
import com.alibaba.yygh.model.hosp.Department;
import com.alibaba.yygh.vo.hosp.DepartmentQueryVo;
import com.alibaba.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * description: DepartmentServiceImpl
 * @author: gql
 * @date: 2021/11
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        // 1.使用fastjson将Map转换为JSON字符串再转换为对象
        Department department = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Department.class);
        if (null == department) {
            throw new YyghException(20001, "数据异常,department的值为null!");
        }

        // 2.查询科室信息是否已经存在
        Department existdepartment = this.departmentRepository.findDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());

        if (null != existdepartment) {
            // 修改
            department.setId(existdepartment.getId());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        } else {
            // 添加
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    /**
     *
     * @param page 当前页
     * @param limit 每页记录数
     * @param departmentQueryVo 查询条件
     * @return
     */
    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        // 1.设置排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        // 2.设置分页数据
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        // 3.条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        // 4.将departmentQueryVo转换为department
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        // 5.封装查询条件
        Example<Department> example = Example.of(department, matcher);

        // 6.执行查询
        Page<Department> pages = departmentRepository.findAll(example, pageable);

        return pages;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        // 1.先根据hoscode和depcode查询到科室信息
        Department department = departmentRepository.findDepartmentByHoscodeAndDepcode(hoscode, depcode);

        // 2.如果不为空才根据id删除
        if (null != department) {
            this.departmentRepository.deleteById(department.getId());
        }
    }

    /**
     * 1.查询医院所有科室列表
     * @param hoscode 医院编号
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        // 1.根据hoscode查询医院科室列表
        List<Department> deptList = this.departmentRepository.findDepartmentByHoscode(hoscode);

        /**
         * 2.根据大科室进行分组
         * Map<String,List<Department>>
         *          key:大科室编号
         *          value:大科室中的记录
         */
        Map<String, List<Department>> departmentMap =
                deptList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        // 3.准备用于数据封装的List<DepartmentVo>
        List<DepartmentVo> finalResult = new ArrayList<>();

        // 4.遍历分组之后的Map集合,封装大科室和小科室
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            // 大科室编号
            String bigCode = entry.getKey();
            // 大科室编号中小科室集合
            List<Department> smallDeptList = entry.getValue();

            // 4.1 封装大科室
            DepartmentVo bigDepartment = new DepartmentVo();
            bigDepartment.setDepcode(bigCode);
            bigDepartment.setDepname(smallDeptList.get(0).getBigname());
            // 4.2 封装小科室 List<Department> 转换为 List<DepartmentVo>
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department : smallDeptList) {
                DepartmentVo departmentVo = new DepartmentVo();
                departmentVo.setDepcode(department.getDepcode());
                departmentVo.setDepname(department.getDepname());
                children.add(departmentVo);
            }
            //4.3 将小科室集合放到大科室的children中
            bigDepartment.setChildren(children);
            finalResult.add(bigDepartment);
        }

        return finalResult;
    }

    /**
     * 2.根据医院编号、部门编号查询部门名称
     * @param hoscode 医院编号
     * @param depcode 部门编号
     * @return
     */
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.findDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            return department.getDepname();
        }
        return null;
    }

    /**
     * 获取科室
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return this.departmentRepository.findDepartmentByHoscodeAndDepcode(hoscode,depcode);
    }


}
